package com.bindatax.core.log;

import com.bindatax.core.log.impl.BinDataxEmptyLogger;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.ServiceLoader;

public class LogOutManager {
    public final static String CR = System.lineSeparator();
    private final static BinDataxEmptyLogger emptyLogger = new BinDataxEmptyLogger();
    private static LogOutInterface _LOG = null;

    public static void initLog(Properties pros,String logSystemType){

        System.out.println("开始获取日志系统实例。");
        try {
            ServiceLoader<LogOutInterface> logOutInterfaceServiceLoader = ServiceLoader.load(LogOutInterface.class);
            List<LogOutInterface> logList = new ArrayList<>();
            for (LogOutInterface log : logOutInterfaceServiceLoader){
                logList.add(log);
            }
            if(logList.isEmpty()){
                throw new RuntimeException("没有找到日志输出实现或加载错误！");
            }else {
                LogOutInterface findLog = null;
                LogOutInterface defaultLog = null;
                if(logList.size() > 1){
                    System.out.println("找到多个日志输出实现:");
                    for (int i = 0; i < logList.size(); i++) {
                        LogOutInterface log = logList.get(i);
                        System.out.println("--->>>" + log.getClass().getName());
                        if(log.getType().equalsIgnoreCase(logSystemType)){
                            findLog = log;
                        }
                        if(log.getType().equalsIgnoreCase(LogOutInterface.TYPE_CONSOLE)){
                            defaultLog = log;
                        }
                    }
                }
                _LOG = findLog == null ? defaultLog : findLog;
            }
            if(_LOG == null){
                throw new RuntimeException("查找日志系统异常。");
            }
            System.out.println("使用日志系统实例是：" + _LOG.getClass().getName());
            _LOG.init(pros);
        }catch (Exception e){
            System.out.println("没有找到日志输出实现或加载错误！");
            throw new RuntimeException(e);
        }
    }
    public static LogOutInterface get() {
        if(_LOG == null){
           return emptyLogger;
        }
        return _LOG;
    }

}
